package com.tmall.testgen.client.genfile;

import java.io.File;
import java.util.List;

import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;

import com.tmall.testgen.client.ClientDataCenter;
import com.tmall.testgen.client.config.TargetProjectConfig;
import com.tmall.testgen.client.genfile.genjava.GenCodeCenter;
import com.tmall.testgen.client.genfile.genproject.ProjectGenerator;
import com.tmall.testgen.client.genfile.genxml.GenXMLCenter;
import com.tmall.testgen.common.bo.interact.back.InterceptInfo;
import com.tmall.testgen.common.util.StringUtil;
import com.tmall.testgen.plugin.ConsoleFactory;
/**
 * @author haojia
 * @date 2014-07-04
 */
public class TotalGenHandler {
	public static String split=File.separator;
	public static String projectPrefix="test-";
	public static String templateRootPath="/com/tmall/testgen/client/genfile/template/";
	/**
	 * 
	 * @param testProjectPath  测试工程路径
	 * @param springConfigPath
	 * @param packageName
	 * @param testSimpleClassName
	 * @param toBeGenInfos
	 * @throws Exception
	 */
	public static String genJavaFile(String testProjectPath,String testClassName,List<InterceptInfo> toBeGenInfos) throws Exception{
		
		VelocityEngine velocityEngine = new VelocityEngine();
		velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
//	    velocityEngine.setProperty("input.encoding", "GBK");
	    velocityEngine.setProperty("output.encoding", "UTF-8");
	    velocityEngine.setProperty(Velocity.RESOURCE_LOADER, "class");
	    velocityEngine.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); 
	    Thread.currentThread().setContextClassLoader(TotalGenHandler.class.getClassLoader());
	    velocityEngine.init();
	     
	     
		//生成工程文件
		String projectPath=ProjectGenerator.genProject(testProjectPath,TargetProjectConfig.getInstance().getTargetProjectName(),testClassName, ClientDataCenter.getInstance().getTestProjectInfo(),velocityEngine,toBeGenInfos);
		
        
		//最新结果刷到工作空间中
		try{
            refreshProject(projectPath);
        }catch(Exception e){
            
        }
		return projectPath;
	}
	
	
	private static void refreshProject(String projectSystemFilePath) {
		projectSystemFilePath = projectSystemFilePath + TotalGenHandler.split
				+ ".project";

		// 项目名称
		String projectName = "";
		File projectSystemFile = new File(projectSystemFilePath);
		IPath path = new Path(projectSystemFile.getPath());
		IProjectDescription description = null;
		if (isDefaultLocation(path)) {
			projectName = path.segment(path.segmentCount() - 2);
			description = IDEWorkbenchPlugin.getPluginWorkspace()
					.newProjectDescription(projectName);
		} else {
			try {
				description = IDEWorkbenchPlugin.getPluginWorkspace()
						.loadProjectDescription(path);
				projectName = description.getName();
			} catch (Exception e) {
				ConsoleFactory.putError(e);
				return;
			}
		}

		final IWorkspace workspace = ResourcesPlugin.getWorkspace();
		final IProject project = workspace.getRoot().getProject(projectName);
		try {
			if (project.exists()) {
				// 如果已经存在 则刷新
				project.refreshLocal(IResource.DEPTH_INFINITE, null);
				return;
			} else {
				project.create(description, null);
				project.open(IResource.BACKGROUND_REFRESH, null);
			}
		} catch (CoreException e) {
			ConsoleFactory.putError(e);
		}
	}

	/**
	 * Returns whether the given project description file path is in the default
	 * location for a project 判断是不是本地的
	 * 
	 * @param path
	 *            The path to examine
	 * @return Whether the given path is the default location for a project
	 */
	private static boolean isDefaultLocation(IPath path) {
		// The project description file must at least be within the project,
		// which is within the workspace location
		if (path.segmentCount() < 2)
			return false;
		return path.removeLastSegments(2).toFile()
				.equals(Platform.getLocation().toFile());
	}
}
